package com.lagou.zk.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
	
    public static DruidDataSource dataSource;

	/**
	 * mysql的url靠外面传进来，其他的信息由配置文件获取
	 * @param mysqlUrl
	 */
	public static void init(String mysqlUrl) {
		Properties prop = new Properties();
		try {
			prop.load(JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
			prop.setProperty("url",mysqlUrl);
			// 关闭原来的
			if(dataSource != null){
				dataSource.close();
			}
			dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(prop);
			System.out.println(dataSource);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 	获取连接
	 * @return
	 */
	public static Connection getConn() {
		Connection connection = null;
		try {
			connection = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}
	/**
	 * 	释放资源
	 * @param conn
	 * @param prep
	 */
	public static void close(Connection conn, PreparedStatement prep) {
		try {
			if(prep != null) {
				prep.close();
			}
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void close(Connection conn, PreparedStatement prep, ResultSet rs) {
		try {
			if(rs != null) {
				rs.close();
			}
			close(conn,prep);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		init("jdbc:mysql://hadoop01:3306/zk?useUnicode=true&characterEncoding=utf8&useSSL=true");
		System.out.println(getConn());
	}
	
}